package com.example.JavaWebApi.core.mqtt;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
@Slf4j
public abstract class AbstractMqttCallBack implements MqttCallback {
    protected MqttConfig config;
    protected MqttClient client;
    protected String topic;
    public AbstractMqttCallBack(MqttConfig config){
        this.config=config;
        this.client=config.getClient(String.valueOf(System.currentTimeMillis()));
    }
    public void subscribe(String topic) throws MqttException {
        this.topic=topic;
        client.subscribe(topic);
        client.setCallback(this);
    }

    @SneakyThrows
    @Override
    public void connectionLost(Throwable throwable) {
        log.error("mqtt connection lost");
        this.client=config.getClient(String.valueOf(System.currentTimeMillis()));
        client.subscribe(topic);
        client.setCallback(this);

    }
}
